package net.javastone.toolkit.core.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import lombok.experimental.UtilityClass;
import net.javastone.toolkit.core.dataformat.BitSetDeserializer;
import net.javastone.toolkit.core.dataformat.BitSetSerializer;
import net.javastone.toolkit.core.dataformat.DataFormatTransfer;

import java.util.BitSet;

/**
 * YAML数据处理工具类
 *
 */
@UtilityClass
public class Yamls {

  private static final ObjectMapper objectMapper;

  static {
    objectMapper = new YAMLMapper();
    objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_INDEX);
    objectMapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    SimpleModule module = new SimpleModule(objectMapper.getClass().getSimpleName(),
        new Version(1, 0, 0, null, null, null));
    module.addSerializer(new BitSetSerializer());
    module.addDeserializer(BitSet.class, new BitSetDeserializer());
    objectMapper.registerModule(module);
  }

  public static JsonNode tree(String yamlString) {
    return of(yamlString).toTreeOrNullNode();
  }

  public static JsonNode toTree(Object object) {
    return of(object).toTreeOrNullNode();
  }

  public static DataFormatTransfer of(Object source) {
    return new DataFormatTransfer(source, objectMapper);
  }
}
